import math
import Image

goc = 45
def rotate(toado,goc):
    radiant = goc*math.pi/180
    x_moi = (toado[0]*math.cos(radiant) - toado[1]*math.sin(radiant)) 
    y_moi = (toado[0]*math.sin(radiant) + toado[1]*math.cos(radiant)) 
    return (x_moi,y_moi)

def translate(point,distance):
    x_moi = point[0]+distance
    y_moi = point[1]+distance
    return (x_moi,y_moi)

def roundUp(x):
    if (x < 0):
        return - roundup(abs(x))
    else:
        return roundup(x)

def roundup(x):
    if (x > int(x)):
        return round(x + 0.5)
    else:
        return x

def rounddown(x):
    if (x > int(x)):
        return int(x)

i = 0
    
    # load the image
    #old = Image.open("C:\Users\\iGee\\workspace\\CGProject\\vamp.jpg")
old = Image.open("4.png")
old.rotate(45).save("outpro.png")

old_pix = old.load()
# get the original width,heigth
print old.size[0],old.size[1]
dinh = [(0,0),
        (old.size[0] -1 ,0),
        (old.size[0]-1,old.size[1]-1),
        (0,old.size[1]-1)]
print dinh[0]
print dinh[1]
print dinh[2]
print dinh[3]
print len(dinh)
dinh1 = []

#xoay 4 goc

for i in dinh:
    dinh1.append(rotate(i,goc))
#kiem tra kich thuoc hinh moi
print dinh1[0]
print dinh1[1]
print dinh1[2]
print dinh1[3]

min_x = dinh1[0][0]
min_y = dinh1[0][1]

max_x = dinh1[0][0]
max_y = dinh1[0][1]

for dinh in dinh1:
    if(dinh[0] < min_x ):
        min_x = dinh[0]
    if(dinh[1] < min_y):
        min_y = dinh[1]
    if(dinh[0] > max_x ):
        max_x = dinh[0]
    if(dinh[1] > max_y):
        max_y = dinh[1]
print min_x,min_y,max_x,max_y

new_width = (int)(roundUp( max_x) - roundUp(min_x) -1)
new_heigth = (int)(roundUp( max_y) - roundUp( min_y))


new = Image.new("RGBA",(new_width,new_heigth))
new_pix = new.load()

'''
for y in range(old.size[1]):
    for x in range(old.size[0]):
        try:            
            newX,newY = rotate((x,y),goc)
            newX -= min_x
            newY -= min_y
            new_pix[int(newX),int(newY)] = old_pix[x,y]
        except IndexError:
            print x,y,newX,newY
'''

'''
Dung
'''
for x in range(new_width):
    for y in range(new_heigth):
        try:
            oldX, oldY = rotate((x  + roundup(min_x),y), -goc)
            oldX, oldY = int(round(oldX)), int(round(oldY))
            if 0 <= oldX and oldX < old.size[0] and 0 <= oldY and oldY < old.size[1]:
                new_pix[x,y] = old_pix[oldX, oldY]
        except Exception:
            print x,y           

new.save("out3.png")
print "xong" 
    
'''    
#pix_new.save("out.png")
        

#print test((1280,800),45)


dinh = [(0,0),(1280,0),(1280,800),(0,800)]
dinh1 = []
for i in dinh:
    dinh1.append(test(i,45))

min_x = dinh1[0][0]
min_y = dinh1[0][1]

max_x = dinh[0][0]
max_y = dinh[0][1]
'''